package member

import (
	"encoding/csv"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"

	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func GetMemberList(c *gin.Context) {
	var data models.Member
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("momUserId"); index != "" {
		data.MomUserId = tools.StrToInt(err, index)
	}
	data.NickName = c.Request.FormValue("nickName")
	data.RealName = c.Request.FormValue("realName")
	data.AccountName = c.Request.FormValue("accountName")
	data.Password = c.Request.FormValue("password")
	data.Phone = c.Request.FormValue("phone")
	data.CardNo = c.Request.FormValue("cardNo")
	data.Province = c.Request.FormValue("province")
	data.City = c.Request.FormValue("city")
	data.Area = c.Request.FormValue("area")
	data.AddressText = c.Request.FormValue("addressText")
	data.AddressSearch = c.Request.FormValue("addressSearch")
	data.Address = c.Request.FormValue("address")
	if index := c.Request.FormValue("isMom"); index != "" {
		data.IsMom = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("mom_id"); index != "" {
		data.MomUserId = tools.StrToInt(err, index)
	}
	data.WxOpenid = c.Request.FormValue("wxOpenid")
	data.WxUnionid = c.Request.FormValue("wxUnionid")
	data.RegisterTime = c.Request.FormValue("registerTime")
	data.UpdateBy = c.Request.FormValue("updateBy")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据查询失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetMember(c *gin.Context) {
	var data models.Member
	data.MemberId, _ = tools.StringToInt(c.Param("memberId"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -1, "数据查询失败："+err.Error(), nil)
		return
	}
	app.OK(c, result, "")
}

func InsertMember(c *gin.Context) {
	var data models.Member
	err := c.ShouldBindJSON(&data)
	data.CreateBy = tools.GetUserIdStr(c)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}
	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据插入失败："+err.Error(), nil)
		return
	}
	app.OK(c, result, "")
}

func UpdateMember(c *gin.Context) {
	var data models.Member
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}
	result, err := data.Update(data.MemberId)
	if err != nil {
		app.ApiResp(c, -1, "数据更新失败："+err.Error(), data)
		return
	}

	app.OK(c, result, "")
}

func DeleteMember(c *gin.Context) {
	var data models.Member

	IDS := tools.IdsStrToIdsIntGroup("memberId", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), nil)
		return
	}
	app.OK(c, nil, msg.DeletedSuccess)
}

//DownMomList

//DownMemberList
func DownMemberList(c *gin.Context) {
	var data models.Member
	var err error
	var pageSize = 50
	var pageIndex = 1

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("momUserId"); index != "" {
		data.MomUserId = tools.StrToInt(err, index)
	}
	data.NickName = c.Request.FormValue("nickName")
	data.RealName = c.Request.FormValue("realName")
	data.AccountName = c.Request.FormValue("accountName")
	data.Password = c.Request.FormValue("password")
	data.Phone = c.Request.FormValue("memberPhone")
	data.CardNo = c.Request.FormValue("cardNo")
	data.Province = c.Request.FormValue("province")
	data.City = c.Request.FormValue("city")
	data.Area = c.Request.FormValue("area")
	data.Address = c.Request.FormValue("address")
	if index := c.Request.FormValue("isMom"); index != "" {
		data.IsMom = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("mom_id"); index != "" {
		data.MomUserId = tools.StrToInt(err, index)
	}
	data.WxOpenid = c.Request.FormValue("wxOpenid")
	data.WxUnionid = c.Request.FormValue("wxUnionid")
	data.RegisterTime = c.Request.FormValue("registerTime")
	data.UpdateBy = c.Request.FormValue("updateBy")

	data.DataScope = tools.GetUserIdStr(c)
	header := []string{"用戶昵称", "会员ID", "手机号", "所在地区", "小区", "社区达人ID", "达人姓名", "累计订单数量", "累计订单金额"} //标题
	cellist := [][]string{
		header,
	}

	result, count, _ := data.GetPage(pageSize, pageIndex)
	cellist = DataToString(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetPage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToString(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "MEMBER_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)
}

// 	var str = "用戶昵称,会员ID,手机号,所在地区,小区,社区达人ID,社区大人姓名,累计订单数量,累计订单金额\n"
func DataToString(list []models.Member, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		context := []string{
			list[i].NickName,
			strconv.Itoa(list[i].MemberId),
			list[i].Phone,
			list[i].Province + "/" + list[i].City + "/" + list[i].Area,
			list[i].Address,
			strconv.Itoa(list[i].MomUserId),
			list[i].MomRealName,
			tools.IntToString(list[i].TotalOrderNums),
			tools.Float64ToString(list[i].TotalPrice),
		}
		data = append(data, context)
	}
	return data
}
